package com.zkca.xf.ui.activity.technicalprotect;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.videogo.constant.IntentConsts;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.zkca.xf.Constants_SP;
import com.zkca.xf.MyApplication;
import com.zkca.xf.R;
import com.zkca.xf.base.BaseTitleActivity;
import com.zkca.xf.model.javabean.SmokeLbean;
import com.zkca.xf.model.javabean.VideoLBean;
import com.zkca.xf.model.javabean.uploadbean.RequestPage;
import com.zkca.xf.presenter.VideoLPersenter;
import com.zkca.xf.ui.activity.baidumap.DrivingRouteOverlayAct;
import com.zkca.xf.ui.activity.yingshi.EZRealPlayActivity;
import com.zkca.xf.ui.activity.yingshi.EZUtils;
import com.zkca.xf.ui.adapter.SingleAdapter;
import com.zkca.xf.ui.adapter.ViewHolder;
import com.zkca.xf.utils.DisplayUtil;
import com.zkca.xf.utils.LogUtil;
import com.zkca.xf.utils.SPUtil;
import com.zkca.xf.utils.SpaceItemDecoration;
import com.zkca.xf.utils.TimeUtils;
import com.zkca.xf.utils.ToastUtils;
import com.zkca.xf.view.FireAlarmLView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;

public class Video_LActivity extends BaseTitleActivity implements FireAlarmLView {
    @BindView(R.id.xrv_erc)
    XRecyclerView xrv_erc;
    @BindView(R.id.wushuju)
    ImageView wushuju;
    private ImageView imgRight;
    private List<VideoLBean.DataBean> dataList;
    private SingleAdapter<VideoLBean.DataBean> adapter;
    VideoLPersenter videoLPersenter;
    int pageNum = 1;
    int pageSize = 10;
    private RequestPage requestPage;
    private LinearLayoutManager linearLayoutManager;
    private String[] permissions = {Manifest.permission.CALL_PHONE};
    private String[] permissions2 = {Manifest.permission.ACCESS_COARSE_LOCATION};
    private EZOpenSDK mEZOpenSDK;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        ButterKnife.bind(this);
        videoLPersenter = new VideoLPersenter(this, this);
        initMyview();
        initResdata(pageNum);
    }

    private void initMyview() {
        setTitleText("视频监控");
        setleftImgVisibility(true);

        dataList = new ArrayList<>();

        mEZOpenSDK = MyApplication.getOpenSDK();
        linearLayoutManager = new LinearLayoutManager(mContext);
        xrv_erc.setLayoutManager(linearLayoutManager);
        xrv_erc.addItemDecoration(new SpaceItemDecoration(DisplayUtil.dip2px(
                mContext, 0.5f)));
        xrv_erc.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                xrv_erc.setLoadingMoreEnabled(true);
                dataList.clear();
                pageNum=1;
                initResdata(pageNum);
            }

            @Override
            public void onLoadMore() {
                pageNum++;
                initResdata(pageNum);
            }
        });

        adapter = new SingleAdapter<VideoLBean.DataBean>(mContext, dataList, R.layout.videolist_item) {

            @Override
            public void convert(ViewHolder holder, VideoLBean.DataBean dataBean, int position) {
                TextView unitName = holder.getView(R.id.unitName);
                String unitName1 = dataBean.getVideoName();
                unitName.setText(unitName1);//单位名称

                TextView installposition = holder.getView(R.id.installposition);
                String installPosition = dataBean.getInstallPosition();
                installposition.setText("" + installPosition);//安装位置

                TextView contact = holder.getView(R.id.contact);
                String contact1 = dataBean.getContact();
                contact.setText("" + contact1);
                TextView telPhone = holder.getView(R.id.telphone);
                final String telphone = dataBean.getTelephone();
                telPhone.setText("" + telphone);//联系方式

                TextView unitaddress = holder.getView(R.id.unitaddress);
                String unitAddress = dataBean.getUnitAddress();
                unitaddress.setText("" + unitAddress);//单位地址

                TextView devstatus = holder.getView(R.id.devstatus);
                int runMode = dataBean.getRunMode();
                if (runMode == 0) {
                    devstatus.setText("生产");
                } else if (runMode == 1) {
                    devstatus.setText("调试");
                } else if (runMode == 2) {
                    devstatus.setText("停用");
                } else if (runMode == 3) {
                    devstatus.setText("过期");
                } else {
                    devstatus.setText("未知");
                }
                final String videoId = dataBean.getVideoId();
                holder.getView(R.id.video_tel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    EZDeviceInfo deviceInfo = mEZOpenSDK.getDeviceInfo(videoId);
                                    final EZCameraInfo cameraInfo = EZUtils.getCameraInfoFromDevice(deviceInfo, 0);

                                    Intent intent1 = new Intent(Video_LActivity.this, EZRealPlayActivity.class);
                                    intent1.putExtra(IntentConsts.EXTRA_CAMERA_INFO, cameraInfo);
                                    intent1.putExtra(IntentConsts.EXTRA_DEVICE_INFO, deviceInfo);
                                    intent1.putExtra("xuliehao",  videoId);
//                            startActivityForResult(intent1, 100);
                                    startActivity(intent1);
                                } catch (BaseException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();

                    }
                });

                final double longitude = dataBean.getLongitude();
                final double latitude = dataBean.getLatitude();
                holder.getView(R.id.iv_lujing).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        final Intent intent = new Intent(mContext, DrivingRouteOverlayAct.class);
                        intent.putExtra("jingdu", longitude);
                        intent.putExtra("weidu", latitude);

                        if (longitude==0.0||latitude==0.0){
                            ToastUtils.show(mContext,"目标点经纬度信息不完善，无法进行线路规划");
                            return;
                        }

                        LogUtil.e("jingdu==",longitude+"weidu=="+latitude);
                        RxPermissions rxPermissions = new RxPermissions(Video_LActivity.this);
                        rxPermissions.request(permissions2)
                                .subscribe(new Consumer<Boolean>() {
                                    @Override
                                    public void accept(@NonNull Boolean granted) throws Exception {
                                        //同意授权
                                        if (granted) {
                                            if (ActivityCompat.checkSelfPermission(Video_LActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                                ToastUtils.show(Video_LActivity.this, "请添加定位权限");
                                                return;
                                            }
                                            startActivity(intent);
                                        } else {//拒绝
                                            ToastUtils.show(Video_LActivity.this, "请添加定位权限");
                                        }
                                    }
                                });
                    }
                });


                holder.getView(R.id.iv_tel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        final Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + telphone));

                        RxPermissions rxPermissions = new RxPermissions(Video_LActivity.this);
                        rxPermissions.request(permissions)
                                .subscribe(new Consumer<Boolean>() {
                                    @Override
                                    public void accept(@NonNull Boolean granted) throws Exception {
                                        //同意授权
                                        if (granted) {
                                            if (ActivityCompat.checkSelfPermission(Video_LActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                                ToastUtils.show(Video_LActivity.this, "请添加手机拨打电话权限");
                                                return;
                                            }
                                            startActivity(intent);
                                        } else {//拒绝
                                            ToastUtils.show(Video_LActivity.this, "请添加手机拨打电话权限");
                                        }
                                    }
                                });

                    }
                });

            }
        };
        xrv_erc.setAdapter(adapter);
    }

    private void initResdata(int pagenum) {
        Map map = new HashMap<String, Object>();
        String Etime = TimeUtils.getTimeL();
        long time = System.currentTimeMillis();//获取系统时间的10位的时间戳
        long days7 = 7 * 24 * 3600 * 1000;
        long etime = time - days7;
        String Btime = TimeUtils.getFormatDateYMD(etime);

//        map.put("BcreateTime", Btime);
//        map.put("EcreateTime", Etime);
        requestPage = new RequestPage();
        requestPage.setAccessId(SPUtil.getString(this, Constants_SP.ACCESSID));
        requestPage.setPageNum(pagenum);
        requestPage.setPageSize(pageSize);
        requestPage.setParam(map);
        requestPage.setTimeStamp(TimeUtils.getTime());
        requestPage.setSign(MyApplication.getInstance().generateSign(requestPage));
        videoLPersenter.getVideo(requestPage);
    }

    @Override
    public void showProgressDialog() {

    }

    @Override
    public void hideProgressDialog() {

    }

    @Override
    public void showError(String msg) {

            wushuju.setVisibility(View.VISIBLE);
            ToastUtils.show(this,msg);

    }

    @Override
    public void getFireAlarm(String s) {
        LogUtil.e("121", s);
        Gson gson = new Gson();
        VideoLBean friealarmLbean = gson.fromJson(s, VideoLBean.class);
        try {
            xrv_erc.refreshComplete();
            xrv_erc.loadMoreComplete();
            if (friealarmLbean.getResult() == 0) {
                List<VideoLBean.DataBean> data = friealarmLbean.getData();
                if (data != null && data.size() > 0) {
                    dataList.addAll(data);
                }
                if (friealarmLbean.getTotalpage() == pageNum) {
                    xrv_erc.setLoadingMoreEnabled(false);
                }
                if (pageNum == 1 && data.size() == 0) {
                    wushuju.setVisibility(View.VISIBLE);
                } else {
                    wushuju.setVisibility(View.GONE);
                }
                adapter.notifyDataSetChanged();
            }else {
                wushuju.setVisibility(View.VISIBLE);
                ToastUtils.show(this,friealarmLbean.getInfo());
            }
        } catch (Exception e) {

        }
    }
}
